#include "dbmanager.h"

#include <QThread>

DBManager &DBManager::getInstance()
{
    static DBManager instance;
    return instance;
}

bool DBManager::logon(MsgDatagram &msg)
{
    QMap<QString,QString> msgMap;
    //验证是否已经注册
    QString sql = QString("SELECT id FROM user WHERE phoneNum = '%1';").arg(msg.m_user.phoneNum);
    QList<QList<QString>> row;
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
        return false;
    msgMap.insert("phoneNum",QString("'%1'").arg(msg.m_user.phoneNum));
    msgMap.insert("password",QString("'%1'").arg(msg.m_user.password));
    msgMap.insert("loginTime",QString("'%1'").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd")));
    msgMap.insert("permissions",QString("'%1'").arg("common"));
    msgMap.insert("loginStatus","'false'");
    if(bSqlite->add("user",msgMap))
    {
        qDebug()<<"用户注册成功！！！"<<endl;
        //更新病人信息表
        bSqlite->add("patientInformation",QMap<QString,QString>{{"phonenum",QString("%1").arg(msg.m_user.phoneNum)}});
        return true;
    }

    else
    {
      qDebug()<<"用户注册失败！！！"<<endl;
      return false;
    }

}

bool DBManager::checkLogin(MsgDatagram &msg)
{
    qDebug()<<__FILE__<<", "<<__FUNCTION__<<" current thread:"<<QThread::currentThread()<<endl;
    qDebug()<<"fcheckLogin msg:"<<msg;
    qDebug()<<"phoneNum:"<<msg.m_user.phoneNum<<" "<<"password"<<msg.m_user.password<<endl;
    QString sql = QString("SELECT password,loginStatus FROM user WHERE phonenum = '%1'").arg(msg.m_user.phoneNum);

    QList<QList<QString>> row;
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
    {
        qDebug()<<"用户登陆状态"<<row.at(0).at(1)<<endl;
        if(row.at(0).at(1) == "false")
        {//用户未重复登陆
            //qDebug()<<"查询到的用户密码:"<<row.at(0).at(0)<<endl;
            if(row.at(0).at(0)!=msg.m_user.password)
            {
                msg.m_logStatus = false;
                msg.m_errorReason = "密码错误";
                qDebug()<<"用户密码错误"<<endl;
                return false;
            }
            else
            {
                msg.m_logStatus = "登陆成功";
                msg.m_logStatus = true;
                qDebug()<<"登陆成功"<<endl;
                this->updateUserLogonStatus(msg.m_user.phoneNum,true);
                return true;
            }
        }
        else
        {
            msg.m_logStatus = false;
            msg.m_errorReason = "用户已登陆";
            qDebug()<<"用户已登陆"<<endl;
            return false;
        }

    }
    else
    {//在数据库中没有找到该用户注册信息
        msg.m_logStatus = false;
        msg.m_errorReason = "用户未注册";
        qDebug()<<"没有该用户"<<endl;
        return false;
    }
    return true;
}

bool DBManager::updateUserLogonStatus(QString phonenum, bool logonStatus)
{
    QString status = logonStatus==true? "true":"false";
    QString sql = QString("UPDATE user SET loginStatus = '%1' WHERE phonenum = '%2';").arg(status).arg(phonenum);
    if(bSqlite->update(sql))
    {
        qDebug()<<"用户状态更新成功"<<endl;
        return true;
    }
    else
    {
        qDebug()<<"用户状态更新失败"<<endl;
        return false;
    }
}

void DBManager::updateAllUserLogonStatus()
{
    QString sql = "UPDATE user SET loginStatus = 'false';" ;
    bSqlite->update(sql);
}

bool DBManager::findUserPassword(MsgDatagram &msg)
{
    QList<QList<QString>> row;
    QString sql = QString("SELECT password FROM user WHERE phonenum = '%1';").arg(msg.m_user.phoneNum);
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
    {
        msg.m_user.password = row.at(0).at(0);
        return true;
    }
    return false;

}

bool DBManager::appointment(MsgDatagram &msg)
{
    //预约
    QMap<QString,QString> orderMap;
    orderMap.insert("phoneNum",QString("'%1'").arg(msg.m_user.phoneNum));
    orderMap.insert("operationType",QString("'%1'").arg(msg.m_opeLineInfo.operation_type));
    //预约号：根据某手术当前排队总人数确定
    QString sql = QString("SELECT operationQueueCount FROM queueinformation WHERE operationType = '%1';").arg(msg.m_opeLineInfo.operation_type);
    QList<QList<QString>> row;
    if(bSqlite->find(sql,&row))
    {
        int orderNum = row.at(0).at(0).toInt()+1;
        msg.m_opeLineInfo.operation_line_num = orderNum;
        orderMap.insert("orderNum",QString::number(orderNum));
        if(bSqlite->add("patienorder",orderMap))
        {
            qDebug()<<"预约成功！！！"<<endl;
            QString updataSql =QString("UPDATE queueinformation SET operationQueueCount = operationQueueCount+1 WHERE operationType = '%1';").arg(msg.m_opeLineInfo.operation_type);
            if(bSqlite->update(updataSql))
            {
                qDebug()<<"手术总人数+1"<<endl;
                return true;
            }
            else
                return false;
        }
    }
    else
    {
        qDebug()<<"预约失败"<<endl;
        return false;
    }
    return true;

}

bool DBManager::cancelappointment(MsgDatagram &msg)
{
    QString where = QString("phonenum = '%1' AND operationType = '%2'; ").arg(msg.m_user.phoneNum).arg(msg.m_opeLineInfo.operation_type);
    if(bSqlite->del("patienorder",where))
    {
        QString sql = QString("UPDATE queueinformation SET operationQueueCount = operationQueueCount-1 WHERE operationType = '%1';").arg(msg.m_opeLineInfo.operation_type);
        if(bSqlite->update(sql))
        {
            return true;
        }

    }
    return false;
}

int DBManager::findOrderNum(QString orderType, QString phonenum)
{
    QString sql = QString("SELECT orderNum FROM patienorder WHERE phonenum = '%1' AND operationType = '%2'; ").arg(phonenum).arg(orderType);
    QList<QList<QString>> row;
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
    {
        return row.at(0).at(0).toInt();
    }
    else return 0;
}

int DBManager::findOrderNum(QString phonenum)
{
    QString sql = QString("SELECT orderNum FROM patienorder WHERE phonenum = '%1'; ").arg(phonenum);
    QList<QList<QString>> row;
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
    {
        return row.at(0).at(0).toInt();
    }
    else return 0;

}

QMap<QString, int> DBManager::findAppointmentInformation(MsgDatagram &msg)
{
    QMap<QString, int> operation_type_num_map;
    QString sql = QString("SELECT operationType,orderNum FROM patienorder WHERE phonenum = '%1';").arg(msg.m_user.phoneNum);
    QList<QList<QString>> row;
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
    {
        for(int i=0;i<row.size();i++)
        {
            operation_type_num_map.insert(row.at(i).at(0),row.at(i).at(1).toInt());
        }
    }
    return operation_type_num_map;

}

QMap<QString, int> DBManager::findOperationTypeCount()
{
    QMap<QString, int> map;
    QString sql = "SELECT operationType,operationQueueCount FROM queueinformation;";
    QList<QList<QString>> row;
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
    {
        for(int i=0;i<row.size();i++)
        {
            map.insert(row.at(i).at(0),row.at(i).at(1).toInt());
        }
    }
    return map;


}

int DBManager::findOperationTypeCount(QString operationType)
{
    QList<QList<QString>> row;
    QString sql = QString("SELECT operationQueueCount FROM queueinformation WHERE operationType = '%1';").arg(operationType);
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
        return row.at(0).at(0).toInt();
}

bool DBManager::updatePatientInfo(MsgDatagram &msg)
{
    QList<QList<QString>> row;
    QString sql = QString("SELECT id FROM patientInformation WHERE phonenum = '%1';").arg(msg.m_patientInfo.p_phonenum);
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
    {//病人信息更新
        QString updatesql = QString("UPDATE patientInformation SET name = '%1',age=%2,sex='%3',nation='%4',bloodType='%5',birthday='%6',IDNumber='%7',diseasesHistory='%8',drugAllergyHistory='%9' WHERE phonenum = '%10';")
                            .arg(msg.m_patientInfo.p_name).arg(QString::number(msg.m_patientInfo.p_age)).arg(msg.m_patientInfo.p_sex)
                            .arg(msg.m_patientInfo.p_nation).arg(CEnum::enumtoString(msg.m_patientInfo.p_bloodtype)).arg(msg.m_patientInfo.p_birthday)
                            .arg(msg.m_patientInfo.p_ID).arg(msg.m_patientInfo.p_diseaseHistory).arg(msg.m_patientInfo.p_drugAllergyHistory).arg(msg.m_patientInfo.p_phonenum);
        if(bSqlite->update(updatesql))
            return true;
    }
    else
    {//病人信息新增
        QMap<QString,QString> patientInfoMap;
        patientInfoMap.insert("name",QString("'%1'").arg(msg.m_patientInfo.p_name));
        patientInfoMap.insert("age",QString("%1").arg(QString::number(msg.m_patientInfo.p_age)));
        patientInfoMap.insert("sex",QString("'%1'").arg(msg.m_patientInfo.p_sex));
        patientInfoMap.insert("nation",QString("'%1'").arg(msg.m_patientInfo.p_nation));
        patientInfoMap.insert("bloodType",QString("'%1'").arg(CEnum::enumtoString(msg.m_patientInfo.p_bloodtype)));
        patientInfoMap.insert("birthday",QString("'%1'").arg(msg.m_patientInfo.p_birthday));
        patientInfoMap.insert("IDNumber",QString("'%1'").arg(msg.m_patientInfo.p_ID));
        patientInfoMap.insert("phonenum",QString("'%1'").arg(msg.m_patientInfo.p_phonenum));
        patientInfoMap.insert("diseasesHistory",QString("'%1'").arg(msg.m_patientInfo.p_diseaseHistory));
        patientInfoMap.insert("drugAllergyHistory",QString("'%1'").arg(msg.m_patientInfo.p_drugAllergyHistory));
        if(bSqlite->add("patientInformation",patientInfoMap))
            return true;
    }







}

QString DBManager::findPatientName(QString phonenum)
{
    QList<QList<QString>> row;
    QString sql = QString("SELECT name FROM patientInformation WHERE phonenum = '%1';").arg(phonenum);
    if(bSqlite->find(sql,&row)&&(!row.isEmpty()))
        return row.at(0).at(0);

}



DBManager::DBManager()
{


}
